<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="160px">
      <!-- <el-form-item v-if="isAdmin">
        <el-button type="primary fr" @click="checkQuire = !checkQuire">设置必填项</el-button>
      </el-form-item> -->
      <el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="上传证件">
              <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" v-model="requireData.identificationImg"></el-checkbox>
              <ImgUpload
                @handleImgSuccess="ficationImgSuccess"
                :uploadConfig="{ lebal: '身份证正面照', prefix: 'identification', form: form, suffix: 'Img' }"
                :required="!!requireData.identificationImg"
              />
              <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" v-model="requireData.identificationBackImg"></el-checkbox>
              <ImgUpload
                :uploadConfig="{ lebal: '身份证背面照', prefix: 'identificationBack', form: form, suffix: 'Img' }"
                :required="!!requireData.identificationBackImg"
              />
              <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" v-model="requireData.identificationInhandImg"></el-checkbox>
              <ImgUpload
                :uploadConfig="{ lebal: '手持身份证合照', prefix: 'identificationInhand', form: form, suffix: 'Img' }"
                :required="!!requireData.identificationInhandImg"
              />
              <el-checkbox v-if="checkQuire && parentData.isCompany" :true-label="1" :false-label="0" v-model="requireData.businessLicenseImg"></el-checkbox>
              <ImgUpload
                @handleImgSuccess="businessImgSuccess"
                :uploadConfig="{ lebal: '社会信用三合一照片', prefix: 'businessLicense', form: form, suffix: 'Img' }"
                :required="!!requireData.businessLicenseImg"
                v-if="parentData.isCompany"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-col :span="12" v-if="parentData.isCompany">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('userName')" v-model="requireData.userName"></el-checkbox>
          <el-form-item label="联系人" prop="userName">
            <el-input v-model.trim="form.userName" @change="(value)=>{form.userName = value.replace(/\s/g,'')}" placeholder="请输入联系人" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="!parentData.isCompany">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('userName')" v-model="requireData.userName"></el-checkbox>
          <el-form-item label="托运人姓名" prop="userName">
            <el-input v-model="form.userName" placeholder="请输入托运人姓名" @change="(value)=>{form.userName = value.replace(/\s/g,'')}" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('phone')" v-model="requireData.phone"></el-checkbox> -->
          <el-form-item label="联系方式" prop="phone">
            <el-input v-model="form.phone" autocomplete="off" placeholder="请输入联系方式" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('upass')" v-model="requireData.upass"></el-checkbox>
          <el-form-item label="密码" prop="upass">
            <el-input
              v-model="form.upass"
              type="password"
              autocomplete="new-password"
              placeholder="请输入密码，默认abcd1234"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parentData.isCompany">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('companyName')" v-model="requireData.companyName"></el-checkbox>
          <el-form-item label="托运单位" prop="companyName">
            <el-input v-model="form.companyName" placeholder="请输入托运单位" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parentData.isCompany">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('businessLicenseImgNumber')" v-model="requireData.businessLicenseImgNumber"></el-checkbox>
          <el-form-item label="统一社会信用代码" prop="businessLicenseImgNumber">
            <el-input v-model="form.businessLicenseImgNumber" placeholder="请输入统一社会信用代码" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parentData.isCompany">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('legalName')" v-model="requireData.legalName"></el-checkbox>
          <el-form-item label="法人代表名称" prop="legalName">
            <el-input v-model="form.legalName" placeholder="请输入法人代表名称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('identificationNumber')" v-model="requireData.identificationNumber"></el-checkbox>
          <el-form-item label="身份证号" prop="identificationNumber">
            <el-input v-model="form.identificationNumber" placeholder="请输入身份证号" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12" v-if="parentData.isCompany && hasTaxOpen">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('myTaxOrgan')" v-model="requireData.myTaxOrgan"></el-checkbox>
          <el-form-item label="主管税务机关" prop="myTaxOrgan" label-width="160px">
            <el-input v-model="form.myTaxOrgan" placeholder="请输入主管税务机关" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('prefix')" v-model="requireData.prefix"></el-checkbox>
          <el-form-item label="简称码" prop="prefix">
            <el-input v-model="form.prefix" placeholder="请输入2-4位纯字母的入驻商简称" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('taxPoint')" v-model="requireData.taxPoint"></el-checkbox>
          <el-form-item label="税点(%)" prop="taxPoint">
            <el-input type="number" v-model="form.taxPoint" placeholder="请输入税点" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('areaList')" v-model="requireData.areaList"></el-checkbox>
          <el-form-item label="通信地址" prop="areaList">
            <el-cascader
              v-model="form.areaList"
              :options="parentData.areaOptions"
              :props="{ value: 'countyCode', label: 'countyName', children: 'children' }"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('address')" v-model="requireData.address"></el-checkbox>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="form.address" placeholder="请输入详细地址" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="!parentData.isCompany && hasTaxOpen">
        <el-col :span="24">
          <el-checkbox v-if="checkQuire" :true-label="1" :false-label="0" class="bigCheckBox" @change="setQuired('myTaxOrgan')" v-model="requireData.myTaxOrgan"></el-checkbox>
          <el-form-item label="主管税务机关" prop="myTaxOrgan" label-width="160px">
            <el-input v-model="form.myTaxOrgan" placeholder="请输入主管税务机关" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="line-height: 36px;"  v-if="!checkQuire">
        <el-col :span="22" :offset="1">
          <div style="padding-bottom: 22px;">
            <el-checkbox
              v-model="form.isMonthlyClient"
              label="是否为月结客户"
              :checked="!!form.isMonthlyClient"
              :false-label="0"
              :true-label="1"
              :disabled="!!form.isEnsure"
              @change="(value) => form.isEnsure = 0"
            />
            <el-checkbox
              v-model="form.isIndependentCheckout"
              label="是否独立核算"
              :checked="!!form.isIndependentCheckout"
              :false-label="0"
              :true-label="1"
              v-if="ctmsShow"
            />
            <el-checkbox
              v-model="form.isLoadConfirm"
              label="是否装货确认"
              :checked="!!form.isLoadConfirm"
              :false-label="0"
              :true-label="1"
              v-if="ctmsShow"
            />
            <el-checkbox
              v-model="form.isUnloadConfirm"
              label="是否卸货确认"
              :checked="!!form.isUnloadConfirm"
              :false-label="0"
              :true-label="1"
              v-if="ctmsShow"
            />
            <el-checkbox
              v-model="form.isReleaseCheck"
              label="货源是否需要平台审核"
              :checked="!!form.isReleaseCheck"
              :false-label="0"
              :true-label="1"
              v-if="ctmsShow"
            />
            <el-checkbox
              v-model="form.isEnsure"
              label="是否需要发货保证金"
              :checked="!!form.isEnsure"
              :false-label="0"
              :true-label="1"
              :disabled="!!form.isMonthlyClient"
              @change="(value) => form.isMonthlyClient = 0"
              v-if="ctmsShow"
            />
          </div>
        </el-col>
        <!-- <el-col :span="4" v-if="form.isEnsure">
          <el-form-item prop="ensureFee">
            <el-input v-model="form.ensureFee" placeholder="请输入保证金" />
          </el-form-item>
        </el-col> -->
      </el-row>
      <el-row v-if="form.isEnsure">
        <el-col :span="5">
          <el-form-item prop="ensureFee" label="发货保证金">
            <el-input
              v-model="form.ensureFee"
              placeholder="请输入保证金"
              :disabled="parentData.hideCheckbox"
            >
              <template slot="append">元</template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-button type="primary" v-if="!checkQuire" plain @click="funcSubmit()">提交</el-button>
    <el-button v-if="checkQuire && isAdmin" type="primary" plain @click="funcSaveSet()">保存必填设置</el-button>
  </div>
</template>
<script>
import { addShipperInfo, getOcr } from "@/api/shipment";
import ImgUpload from "@/components/ImgUpload";
import {
  validatePhone,
  validateIDNumber,
  validateBusinessLicenseImgNum,
  validatePrefix,
} from "@/utils/validate.js";
import {findByFieldFrom,updateFieldRequired} from "@/api/required";
import { getRole } from "@/utils/getRole";
import request from "@/utils/request";
import { mayDecimal,istenOrEighteen,isBetweenHundred} from "@/utils/validate4Form.js";
export default {
  name: "ShipmentAdd",
  components: {
    ImgUpload,
  },
  props: {
    parentData: {
      type: Object,
      default() {
        return {
          areaOptions: [],
          isCompany: false,
        };
      },
    },
  },
  data() {
    return {
      ctmsShow: true, //显示独立核算,显示确认装货,显示卸货确认,显示平台审核,显示发货保证金
      hasTaxOpen: false,//是否开启税务
      // 必填功能
      checkQuire: false,
      isAdmin: false,
      requireData: {},
      form: {
        staffType: 0, // 默认类型
        userName: "",
        legalName: "",
        upass: "",
        companyName: "",
        businessLicenseImgNumber: "", // 信用代码
        prefix: "",
        taxPoint: 0,
        areaList: [],
        address: "",
        identificationImg: "",
        identificationBackImg: "",
        identificationInhandImg: "",
        businessLicenseImg: "",
        isIndependentCheckout: 0,
        isLoadConfirm: 0,
        isUnloadConfirm: 0,
        isReleaseCheck: 1,
        isMonthlyClient: 0,
        isEnsure: 0,
        ensureFee: "",
        needVerifyCompany: "",
        myTaxOrgan: "",
      },
      rules: {
        userName: [{ required: false, message: "请输入托运人姓名", trigger: "blur" },
        { max:64, message: "长度不能超过64个字符", trigger: "blur" }],
        legalName: [{ required: false, message: "请输入法人代表名称", trigger: "blur" },
        { max:64, message: "长度不能超过64个字符", trigger: "blur" }],
        phone: [
          {
            required: true,
            validator(rule, value, callback) {
              validatePhone(value)
                ? callback()
                : callback(new Error("手机号格式有误"));
            },
            trigger: "blur",
          },
        ],
        identificationNumber: [
          {
            required: false,
            message: "请输入身份证号",
            trigger: "blur",
          },
          {
            validator(rule, value, callback) {
              validateIDNumber(value)? callback() : callback(new Error("请输入正确的身份证号"));
            },
            trigger: "blur"
          }
        ],
        upass: [
          { required: false, message: "请输入密码", trigger: "blur" },
          { min: 8,message: "数字与字母组合，至少8 个字符", trigger: "blur" }
        ],
        companyName: [
          { required: false, message: "请输入托运单位", trigger: "blur" },
          { max: 100, message: "长度不能超过100个字符", trigger: "blur" }
        ],
         businessLicenseImgNumber: [
          {
            required: false,
            message: "请输入统一社会信用代码",
            trigger: "blur"
          },
          { validator: istenOrEighteen, trigger: "blur" },
        ],
        prefix: [
          { required: false, message: "请输入入驻商简称", trigger: "blur" },
          {
            validator(rule, value, callback) {
              validatePrefix(value)
                ? callback()
                : callback(new Error("请输入2-4位纯字母的入驻商简称"));
            },
            trigger: "blur",
          },
        ],
        taxPoint: [
          { required: false, message: "请输入税点", trigger: "blur" },
          { validator: isBetweenHundred, trigger: "blur" }
        ],
        address: [
          { required: false, message: "请输入详细地址", trigger: "blur" },
          { min: 1, max:256, message: "长度在 1 到 256个字符", trigger: "blur" }
        ],
        areaList: [
          { required: false, message: "请选择通信地址", trigger: "change" },
        ],
        ensureFee: [
          { required: false, message: "请输入保证金", trigger: "blur" },
          { validator:mayDecimal, trigger: 'blur' }
        ],
        myTaxOrgan: [
          {
            required: false,
            message: "请输入所属主管税务机关",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    const partyType = this.$store.getters.party.partyType
    this.isAdmin = partyType == 'SUPER_ADMIN' || partyType == 'PLAT_ADMIN' || partyType == 'STAFF'
    this.checkQuire = !!this.$route.query.checkQuire
    this.findByFieldFrom()
    this.ctmsShow = !getRole();
    this.form.staffType = this.parentData.isCompany ? 1 : 0;
    /*if (this.parentData.isCompany) {
      request({
        url: `/ntocc-basic-api/shipment/companyVerify`,
        method: "get",
      }).then((response) => {
        this.form.needVerifyCompany = response.data;

      });
    }*/
    request({
      url: `/arpa-basic-api/industry/isOpen `,
      method: "get",
    }).then((response) => {
      this.hasTaxOpen= response.data == 1 ? true : false
    });
  },
  methods: {
    // 查询必填项
    async findByFieldFrom(){
      let isCompany = this.$route.query.company?'shipmentCompany':'shipment'
      let response = await findByFieldFrom({fieldFrom:isCompany})
      this.requireData = response.data
      for(let key in this.requireData){
       if(this.rules[key])this.rules[key][0].required = !!this.requireData[key];
      }
    },
    // 保存必填设置 
    async  funcSaveSet(){
      const rLoading = this.openLoading();
      let isCompany = this.$route.query.company?'shipmentCompany':'shipment'
      let response = await updateFieldRequired({message:this.requireData,fieldFrom:isCompany})
      rLoading.close();
      this.$message.success(response.msg)
      // this.checkQuire = false
    },
    // 设置必填
    setQuired(key){
      this.rules[key][0].required = !!this.requireData[key];
    },
    // 提交
    funcSubmit() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          const rLoading = this.openLoading();
          this.form.ensureFee = this.form.isEnsure ? this.form.ensureFee : 0;
          this.form.staffType = this.parentData.isCompany ? 1 : 0;
          this.form.taxPoint = parseFloat(this.form.taxPoint)
          addShipperInfo(this.form).then((response) => {
            rLoading.close();
            this.$message({ message: response.msg, type: "success" });
            this.jumpToList();
          });
          /*if (this.form.needVerifyCompany && this.form.staffType === 1) {
            request({
              url: `/ntocc-basic-api/shipment/verifyCompany`,
              method: "get",
              params: this.form,
            }).then((response) => {
              const res = response.data;
              if (res.pass === 1) {
                this.form.verifyCompany = 1;
                this.form.ensureFee = this.form.isEnsure
                  ? this.form.ensureFee
                  : 0;
                this.form.staffType = this.parentData.isCompany ? 1 : 0;
                addShipperInfo(this.form).then((response) => {
                  rLoading.close();
                  this.$message({ message: response.msg, type: "success" });
                  this.jumpToList();
                });
              } else {
                this.form.verifyCompany = 0;
                this.$confirm(res.msg + "，是否继续保存?", "提示", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning",
                })
                  .then(() => {
                    const rLoading = this.openLoading();
                    this.form.ensureFee = this.form.isEnsure
                      ? this.form.ensureFee
                      : 0;
                    this.form.staffType = this.parentData.isCompany ? 1 : 0;
                    addShipperInfo(this.form).then((response) => {
                      rLoading.close();
                      this.$message({ message: response.msg, type: "success" });
                      this.jumpToList();
                    });
                  })
                  .catch(() => {
                    return;
                  });
              }
            });
          } else {
            this.form.verifyCompany = 1; //如果设置不需要验证三要素则默认是验证通过状态
            this.form.ensureFee = this.form.isEnsure ? this.form.ensureFee : 0;
            this.form.staffType = this.parentData.isCompany ? 1 : 0;
            addShipperInfo(this.form).then((response) => {
              rLoading.close();
              this.$message({ message: response.msg, type: "success" });
              this.jumpToList();
            });
          }*/
        }
        else {
          this.$message.error("请输入有效值!");
        }

        });
      },
      // 跳转
    jumpToList() {
      if (this.form.staffType === 1) {
        // 企业
        this.$router.push({
          path: "/basicInfo/shipment/shipmentCompanyManage",
        });
      } else {
        // 个人
        this.$router.push({
          path: "/basicInfo/shipment/shipmentManage",
        });
      }
    },
      // 身份证正面识别
      async ficationImgSuccess(url){
        let res = await getOcr({image:url, ocrType:'ocrIdidentityCardFront'})
        let data = res.data
        if(data.name){
          if(this.parentData.isCompany){
            this.form.legalName = data.name
          }else{
            this.form.userName = data.name
          }
        }
        data.identity?this.form.identificationNumber = data.identity:null
        this.form.staffType!='1' && data.address?this.form.address = data.address:null
        if(data.provinceCode && this.form.staffType!='1'){
          this.$set( this.form ,'provinceCode', data.provinceCode)
          this.$set( this.form ,'cityCode', data.cityCode)
          this.$set( this.form ,'countyCode', data.countyCode)
          this.$set( this.form ,'areaList', [data.provinceCode,data.cityCode,data.countyCode]);
        }
      },
      // 社会信用识别
      async businessImgSuccess(url){
        let res = await getOcr({image:url, ocrType:'ocrBusinessLicense'})
        let data = res.data
        if (data.creditNum !== "无") {
          this.$set(this.form, "businessLicenseImgNumber", data.creditNum);
        }
        if (data.companyName && data.companyName != "无") {
          this.$set(this.form, "companyName", data.companyName);
        }
      }
    },
};
</script>
<style lang="scss" scoped>
.el-cascader {
  width: 100%;
}
</style>
